/*
 * Copyright (c) 2005, 2014 vacoor
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 */
package org.vacoor.nothing.web.misc.log.spring;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import org.vacoor.nothing.web.misc.log.Log;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author vacoor
 */
public class LogInterceptor extends HandlerInterceptorAdapter {
    private static final Logger LOGGER = LoggerFactory.getLogger(LogInterceptor.class);

    // controller 执行之前
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        return super.preHandle(request, response, handler);
    }

    // controller 执行之后
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        if (!(handler instanceof HandlerMethod)) {
            return;
        }

        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Log log = handlerMethod.getMethodAnnotation(Log.class);

        if (log == null) {
            return;
        }

        String message = log.value();
        /*
        StdRequestContext ctx = null;// StdRequestContext.getContext();
        if (ctx != null) {
            message = ctx.resolve(message);
        } else {
            LOGGER.warn("StdRequestContext is not setting");
        }
        */

        final String logMessage = message;
        // TODO NEW THREAD WRITE LOG
        Thread logThread = new Thread() {
            public void run() {
                LOGGER.debug(logMessage);
            }
        };

        logThread.setDaemon(true);
        logThread.start();

        super.postHandle(request, response, handler, modelAndView);
    }

    // controller 执行完成(这里可以获取model信息)
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        super.afterCompletion(request, response, handler, ex);
    }
}
